function [pixels] = innerBorder(image, value)
%INNERBORDER return the pixels that belong to the inner border of the image
% Pre: 	the image have at least one margin column and one margin row of zeros
% 		the image have no isolated pixels

% Save image size
xSize = size(image, 1);
ySize = size(image, 2);

% We find the first top-left pixel of the object
[rows columns] = find(image == value);
rvalue = min(rows);
% we get all the values that are in the lowest row
rindexs = rows == rvalue;
cvalues = columns(rindexs);
% we get the lowest column from the lowest row
cvalue = min(cvalues);

% Setting for the loop
currentPixel = [cvalue ; rvalue];
border = currentPixel;
finish = false;
dir = 7;
searchDir = 7;

%imshow(image)
%hold on

while (finish == false)
	
	% We calculate the initial searching direction
	if (mod(dir,2) == 0)
		searchDir = mod(dir + 7, 8);
	else
		searchDir = mod(dir + 6, 8);
	end
	
	% We start searching 3 x 3 neighbours from the currentSearchPixel
	currentSearchPixel = currentPixel + getDirection(searchDir);
	found = false;
	while(found == false)
		
		% we update the current pixel in the search
		currentSearchPixel = currentPixel + getDirection(searchDir);
		currentSearchValue = image(currentSearchPixel(2), currentSearchPixel(1));
		fits = currentSearchPixel(1) > 1 && currentSearchPixel(2) > 1 && currentSearchPixel(1) < ySize && currentSearchPixel(2) < xSize;		
		
		% See whether it contains an object pixel and if it is inside the image
		if (fits && value == currentSearchValue)
			% We found an image pixel
			%plot(currentSearchPixel(1), currentSearchPixel(2), 'o')
			found = true;
			currentPixel = currentSearchPixel;
			border = [border currentPixel];
			dir = searchDir;
		else
			searchDir = mod(searchDir + 1, 8);
		end
	end
    
	% Check whether we computed all the boundary (final condition)
    if (size(border, 2) > 2)
		first = border(:, 1);
		second = border(:, 2);
		last = border(:, size(border, 2));
		secondLast = border(:, size(border, 2)-1);
		if (isequal(first, secondLast) && isequal(last, second))
			finish = true;
		end
    end 
end

% Erase the repeated boundary pixels
pixels = border(:, 1:size(border, 2)-2);

end
